package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.http.util.TextUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.health.commons.PropertiesService;
import com.health.db.model.CourseShareLedger;
import com.health.db.model.UserLIST;
import com.health.db.service.user.ICourseShareLedgerService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GetOpenIdMiNiReq;
import com.health.mapp.bean.GetOpenIdMiNiResp;
import com.health.mapp.bean.Header;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import com.wxtools.api.IMiniService;
import com.wxtools.bean.MiniJsCode2SessionResult;

/**
 * 获取小程序userId
 * @author yuchong
 */
public class GetOpenIdMiNiImpl implements ActionInterface{

    private IUserLISTService userLISTService;
    private IMiniService miniService;
    
	@Autowired
	private ICourseShareLedgerService courseShareLedgerService ;

    private static Logger logger = Logger.getLogger(GetOpenIdMiNiImpl.class);

    @Override
    public Response execute(Header header, Object reqBean) throws Exception {


    	GetOpenIdMiNiReq req = (GetOpenIdMiNiReq) reqBean;
    	GetOpenIdMiNiResp _resp = new GetOpenIdMiNiResp();

        if (TextUtils.isEmpty(req.getCode()))
        {
            _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);

            return _resp;
        }

        try {
        	
        	MiniJsCode2SessionResult tokenResult=miniService.jsCode2SessionResult(req.getCode());
            
            /*WxUserGet userGet = new WxUserGet();
            
            userGet.setOpenid(tokenResult.getOpenid());
            WxUser wxUserInfo = miniService.getUserInfoByOpenId(userGet);*/
            
          /*  if (null != wxUserInfo) {*/
            	
				
				  List<UserLIST> userList= userLISTService.selectByWXOpenid(tokenResult.getOpenid());
				  
				  //判断是否已注册
				  if (userList.size()>0) {
					  _resp.setUserLIST(userList.get(0));
					  CourseShareLedger courShareLedge = courseShareLedgerService.selectByUserId(userList.get(0).getUserid());
						
						if (null!=courShareLedge&&null!=courShareLedge.getBalanceTotal()) {
							_resp.setBalance(String.valueOf(courShareLedge.getBalanceTotal().setScale(2,  BigDecimal.ROUND_HALF_UP)));
						}
					  
				  }else{
					  
				  Date now = DateUtils.now();
                  UserLIST userLIST = new UserLIST();
                  userLIST.setUserName("");
                 /* userLIST.setUserName(wxUserInfo.getNickname());*/
                  userLIST.setApptoken("");
                  userLIST.setUserNo("");
                  userLIST.setPasswordCreateDate(now);
                  userLIST.setLoginDatetime(now);
                  userLIST.setLogoutDatetime(now);
                  userLIST.setPassword("01000000180145C6B29558F1322B63A163FA2A293504E5496FC31142");
                  userLIST.setCreateDate(now);
                  userLIST.setUpdateDate(now);
              	  userLIST.setRegisterDate(now);
                  userLIST.setTypeid(1);
                  userLIST.setTypeName("用户");
                  userLIST.setIsUsedFlag((short) 1);
                  userLIST.setIconUrl(PropertiesService.getString("iconUrl.userDefaultUrl").trim());
                  //userLIST.setRunstatusid((short) 2);
                  userLIST.setWxopenid(tokenResult.getOpenid());
                  userLIST.setUnionid(tokenResult.getUnionid());
                  userLISTService.insertUser(userLIST);
                  _resp.setUserLIST(userLIST);
				  }
            	
//            }
            _resp.setTokenResult(tokenResult);

        }catch (Exception e)
        {
            logger.error(e.getMessage());
            _resp.setErrorCode(-1);
            _resp.setErrorMsg("code error");
            logger.info("code error");
        }

        return _resp;
    }

	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}

	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	public IMiniService getMiniService() {
		return miniService;
	}

	public void setMiniService(IMiniService miniService) {
		this.miniService = miniService;
	}

	public ICourseShareLedgerService getCourseShareLedgerService() {
		return courseShareLedgerService;
	}

	public void setCourseShareLedgerService(
			ICourseShareLedgerService courseShareLedgerService) {
		this.courseShareLedgerService = courseShareLedgerService;
	}
    
}
